package cn.online.taxi.order.service.service.impl;

import cn.online.taxi.common.constant.RedisKeyConstant;
import cn.online.taxi.common.exception.OnlineTaxiException;
import cn.online.taxi.common.jedis.JedisClient;
import cn.online.taxi.driver.user.service.service.DriverInfoService;
import cn.online.taxi.manager.dto.front.Order;
import cn.online.taxi.manager.mapper.TbDriverMapper;
import cn.online.taxi.manager.pojo.TbDriver;
import cn.online.taxi.order.service.service.GrabService;
import cn.online.taxi.order.service.service.OrderService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author BinBini
 * @Date 2021/4/7 10:00
 * @Version 1.0
 */
@Service(accesslog = "grabRedisRedissonService")
public class GrabRedisRedissonService implements GrabService {

    @Reference
    private OrderService orderService;
    @Reference
    private DriverInfoService driverInfoService;
    @Resource
    private TbDriverMapper tbDriverMapper;
    @Autowired
    private JedisClient jedisClient;
    @Value("1000")
    private Integer ORDER_RECEIVING_EXPIRE;

    @Override
    public boolean grabOrder(String orderNumber, Integer driverId, String driverToken) {
        TbDriver tbDriver = tbDriverMapper.selectByPrimaryKey(driverId);
        if (tbDriver == null) {
            throw new OnlineTaxiException("没有该司机");
        }
        String orderJSON = jedisClient.get(RedisKeyConstant.GRAB_LOCK_ORDER_KEY_PRE + ":" + orderNumber);
        Order order = new Gson().fromJson(orderJSON, Order.class);
        // 司机接单,修改订单状态
        order.setDriverId(tbDriver.getId());
        order.setDriverStatus(1);
        order.setDriverPhone(tbDriver.getPhone());
        order.setCarId(tbDriver.getCarId());
        order.setDriverGrabTime(new Date());
        order.setStatus(2);
        order.setDriverToken(driverToken);
        // 抢单成功, 删除派单信息
        jedisClient.del(RedisKeyConstant.GRAB_LOCK_ORDER_KEY_PRE + ":" + order.getOrderNumber());
        // 接单信息写入redis, key: "ORDER:orderNumber" value: "order"
        jedisClient.set(RedisKeyConstant.ORDER_KEY_PRE + ":" + order.getOrderNumber(), new Gson().toJson(order));
        jedisClient.expire(RedisKeyConstant.ORDER_KEY_PRE + ":" + order.getOrderNumber(), ORDER_RECEIVING_EXPIRE);
        return true;
    }
}
